package org.example.verificatiocode.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.verificatiocode.model.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/VerificationCode")   ////使用 @RequestMapping 标注的方法只有在被 HTTP 请求访问时才会被执行
public class VerificationCodeController {
    @Autowired
    private Captcha captcha;

    @RequestMapping("/getVerificationCode")
    public void getVerificationCode(HttpServletResponse response, HttpSession session){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight());
        //获取验证码的值
        String code = lineCaptcha.getCode();
        System.out.println("生成的验证码为: " + code);

        //存储session
        session.setAttribute(captcha.getSession().getKey(), code);
        session.setAttribute(captcha.getSession().getDate(),new Date());

        try {
            lineCaptcha.write(response.getOutputStream());
            //设置格式
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");

            //输出code
            System.out.println(lineCaptcha.getCode());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(@RequestParam("captcha")String captchaCode, HttpSession session){
        System.out.println("用户输入的验证码为: " + captchaCode);

        //判断验证码是否为空
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }

        //获取生成的验证码
        String code = (String)session.getAttribute(captcha.getSession().getKey());

        //获取验证码有效时间
        Date date = (Date)session.getAttribute(captcha.getSession().getDate());

        return Objects.equals(code, captchaCode) && ((System.currentTimeMillis() - date.getTime()) < 120 * 1000);
    }

}
